//管理用户数据相关
import { mergeCartApi } from '@/api/cart'
import { loginApi } from '@/api/user'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useCartStore } from './cart'

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  //state 用户信息
  const userInfo = ref({})

  //action 登录获得用户信息
  const getUserInfo = async ({ account, password }) => {
    const res = await loginApi({ account, password })
    // console.log(res.result)
    userInfo.value = res.result
    //合并购物车
    await mergeCartApi(cartStore.cartList.map((item) => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
    cartStore.updateCartList()
  }

  //action 退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    //清除购物车数据
    cartStore.clearCart()
  }

  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }

}, {
  persist: true
})